<?php
/**
 * BaseAPI - 所有API的基类
 * 提供通用的认证、错误处理等功能
 */

require_once '../config.php';

abstract class BaseAPI {
    protected $db;
    protected $currentUser = null;
    
    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }
    
    /**
     * 获取Authorization头中的Token
     */
    protected function getAuthToken() {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
            return $matches[1];
        }
        
        return null;
    }
    
    /**
     * 要求认证 - 验证Token并返回用户信息
     */
    protected function requireAuth() {
        $token = $this->getAuthToken();
        
        if (!$token) {
            sendErrorResponse('未提供认证令牌', 401);
        }
        
        $stmt = $this->db->prepare("
            SELECT u.*, s.expires_at 
            FROM users u 
            JOIN user_sessions s ON u.id = s.user_id 
            WHERE s.session_token = ? AND s.expires_at > NOW()
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if (!$user) {
            sendErrorResponse('无效或过期的认证令牌', 401);
        }
        
        if ($user['status'] !== 'active') {
            sendErrorResponse('账户已被禁用', 403);
        }
        
        $this->currentUser = $user;
        return $user;
    }
    
    /**
     * 可选认证 - 如果有Token则验证，没有则返回null
     */
    protected function optionalAuth() {
        try {
            return $this->requireAuth();
        } catch (Exception $e) {
            return null;
        }
    }
    
    /**
     * 检查用户是否是资源的所有者
     */
    protected function checkOwnership($table, $resourceId, $userIdField = 'user_id') {
        $stmt = $this->db->prepare("SELECT $userIdField FROM $table WHERE id = ?");
        $stmt->execute([$resourceId]);
        $result = $stmt->fetch();
        
        if (!$result) {
            sendErrorResponse('资源不存在', 404);
        }
        
        if ($result[$userIdField] != $this->currentUser['id']) {
            sendErrorResponse('无权访问此资源', 403);
        }
        
        return true;
    }
    
    /**
     * 处理异常并返回适当的错误响应
     */
    protected function handleException(Exception $e, $context = '') {
        $message = $e->getMessage();
        logActivity("API错误 [$context]: $message", 'ERROR');
        
        // 根据异常类型返回不同的状态码
        if (strpos($message, '不存在') !== false || strpos($message, 'not found') !== false) {
            sendErrorResponse($message, 404);
        } elseif (strpos($message, '无权') !== false || strpos($message, 'forbidden') !== false) {
            sendErrorResponse($message, 403);
        } elseif (strpos($message, '认证') !== false || strpos($message, 'auth') !== false) {
            sendErrorResponse($message, 401);
        } else {
            sendErrorResponse('服务器内部错误', 500);
        }
    }
    
    /**
     * 验证资源所属并获取资源
     */
    protected function getOwnedResource($table, $id, $columns = '*') {
        $stmt = $this->db->prepare("SELECT $columns FROM $table WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $this->currentUser['id']]);
        $resource = $stmt->fetch();
        
        if (!$resource) {
            sendErrorResponse('资源不存在或无权访问', 404);
        }
        
        return $resource;
    }
    
    /**
     * 抽象方法 - 子类必须实现
     */
    abstract public function handleRequest();
}
?>

